package com.gqr.threadlocal;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:ThreadLocalNormalUsage06
 * author:guqingrong
 * Date:2024-05-08 21:27
 * Description:演示ThreadLocal用法2:避免传递参数的麻烦
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class ThreadLocalNormalUsage06 {

    public static void main(String[] args) {
        new Service1().process();
    }
}


// 比如从拦截器中获取token 根据token找出对应的用户 放进threadLocal里
class Service1 {
    public void process() {
        User user = new User("超哥");
        UserContextHolder.holder.set(user);
        new Service2().process();
    }
}

class Service2 {
    public void process() {
        User user = UserContextHolder.holder.get();
        System.out.println("Service2拿到用户名" + user.name);
        // 清空threadLocal
        UserContextHolder.holder.remove();
        new Service3().process();
    }
}

class Service3 {
    public void process() {
        User user = UserContextHolder.holder.get();
        System.out.println("Service3拿到用户名" + user.name);

        /**
         *  假设Service3 是整个调用链路最后的调用  那么我们要删除ThreadLocal 防止内存泄漏
         */
        UserContextHolder.holder.remove();
    }
}

class UserContextHolder {
    public static ThreadLocal<User> holder = new ThreadLocal<>();
}

class User {
    public String name;

    public User(String name) {
        this.name = name;
    }
}
